class Banner {
    constructor() {
        this.main = $(".images"); // 放图片的盒子
        this.sliders = $(".slider-panel"); // 图片伪数组
        this.page = $(".slider-item"); // 分页按钮
        this.btn_next = $(".slider-next"); // 下一页按钮
        this.btn_prev = $(".slider-pre"); // 上一页按钮
        this.sideBanner = $("#SideBanners"); // 大框

        this.timer = null; //定时器清空
        this.nowIndex = 0; //当前图片索引

        this.init();
    }

    init() {
        // 为左右按钮添加鼠标事件
        this.btnEvent();
        // 开始先执行一遍动画
        this.animation();
        // 添加分页功能
        this.pagination();
        // 添加自动轮播
        this.autoPlay();
    }

    // 为左右按钮添加鼠标事件
    btnEvent() {
        // 左右按钮添加hover效果
        this.sideBanner.mouseenter($.proxy(function() {
            clearInterval(this.timer);
            $(".slider-page").css("display", "block");
        }, this));
        this.sideBanner.mouseleave($.proxy(function() {
            this.autoPlay();
            $(".slider-page").css("display", "none");
        }, this));
        // 左右按钮添加侦听事件
        this.btn_prev.on("click", $.proxy(this.prevIndex, this));
        this.btn_next.on("click", $.proxy(this.nextIndex, this));
    }

    nextIndex() {
        this.nowIndex === this.sliders.length - 1 ? (this.nowIndex = 0) : this.nowIndex++;
        this.animation();
    }

    prevIndex() {
        this.nowIndex === 0 ? (this.nowIndex = this.sliders.length - 1) : this.nowIndex--;
        this.animation();
    }

    animation() {
        this.sliders.css("opacity", 0).removeClass("current");
        this.sliders.eq(this.nowIndex).addClass("current").animate({
            opacity: 1
        }, 2000);
        this.page.removeClass("current1")
        this.page.eq(this.nowIndex).addClass("current1");
    }

    pagination() {
        $(".wy-slide-nav").click($.proxy(function(e) {
            if (e.target.nodeName === "SPAN") {
                this.page.removeClass("current1");
                e.target.className += " current1";
                $.each(this.page, $.proxy(function(index, item) {
                    if (item === e.target) {
                        this.nowIndex = index;
                    }
                }, this));
                this.animation();
            }
        }, this));
    }

    autoPlay() {
        clearInterval(this.timer);
        var evt = this.creatEvent("click");
        this.timer = setInterval($.proxy(function() {
            document.querySelector(".slider-next").dispatchEvent(new Event("click"));
        }, this), 5000)
    }

    creatEvent(evt) {
        let event = new Event(evt, {
            bubbles: true,
            cancelable: true
        })
        return event;
    }
}

new Banner();